﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace WpfWordsLearner.ViewModels
{
	public class UncompressVM : BaseViewModel
	{
		private string m_fileToDecompress;

		public string FileToDecompress
		{
			get { return m_fileToDecompress; }
			set { m_fileToDecompress = value; OnPropertyChanged(() => FileToDecompress); }
		}

		public ICommand ChooseCommand { get { return new WpfWordsLearner.Helper.BaseCommand(Choose); } }

		private void Choose()
		{
			Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
			ofd.InitialDirectory = App.pathToContent;
			if (ofd.ShowDialog() == true)
			{
				FileToDecompress = ofd.FileName;
			}
		}

		public ICommand DecompressCommand { get { return new WpfWordsLearner.Helper.BaseCommand(Decompress); } }

		private void Decompress()
		{
			CompressionModule zip = new CompressionModule();

			MergeModule merge = new MergeModule();

			string dir = System.IO.Path.Combine(App.pathToContent, "Tmp");

			if (!System.IO.Directory.Exists(dir))
				System.IO.Directory.CreateDirectory(dir);

			zip.Unompress(FileToDecompress, dir);

			foreach (string unzipFile in System.IO.Directory.EnumerateFiles(dir, "*.xml"))
			{
				foreach (string file in System.IO.Directory.EnumerateFiles(dir, "*.xml"))
				{
					if (string.Compare(System.IO.Path.GetFileName(unzipFile), System.IO.Path.GetFileName(file), true) == 0)
					{
						merge.Merge(file, unzipFile);
						System.IO.File.Delete(unzipFile);
					}
				}
			}

			if (System.IO.Directory.Exists(dir))
				System.IO.Directory.Delete(dir, true);

			zip = null;
			merge = null;
		}
	}
}
